import React, { Component } from 'react';
import { Tab, Table, Pagination, Icon, Loading, Transfer, Message } from '@alifd/next';
import BasicDetailInfo from './components/BasicDetailInfo';
import DataBinder from '@icedesign/data-binder';
import Scrollbar from 'smooth-scrollbar';
import FoundationSymbol from '@icedesign/foundation-symbol';
import './Reservation.scss'


const getData = () => {
  return Array.from({ length: 10 }).map((item, index) => {
    // return {
    //   name: ['淘小宝', '淘二宝'][random(0, 1)],
    //   level: ['普通会员', '白银会员', '黄金会员', 'VIP 会员'][random(0, 3)],
    //   balance: random(10000, 100000),
    //   accumulative: random(50000, 100000),
    //   regdate: `2018-12-1${random(1, 9)}`,
    //   birthday: `1992-10-1${random(1, 9)}`,
    //   store: ['余杭盒马店', '滨江盒马店', '西湖盒马店'][random(0, 2)],
    // };
    return {
      id: index + 1,
      orderID: `12022123${index}`,
      name: '张一峰',
      title: '主治医师',
      date: `2018-06-${index + 1}`,
      endDate: `2018-06-${index + 1}`,
      validData: `2018-06-${index + 1}`,
      category: '皮肤科',
      state: '已审核',
      approver: '刘建明',
      approvalData: `2018-06-${index + 1}`,
    };
  });
};

const tabs = [
    { tab: '表格交互', key: 0,},
];

let scrollbarObj;

@DataBinder({
  dataList: {
    url: 'http://10.10.37.57:4444/mock/search1.json',
    type: 'post',
    data: {
      page: 1,
      pageSize: 20,
    },
    defaultBindingData: {
      // 配置接口返回数据的字段的初次默认值
      no: '',
      createTime: '',
      productName: '',
      reservationAmountStr: '',
      reservationDate: '',
      customerName: '',
      advisorName: '',
      advisorMobile: '',
      statusStr: '',
      reserveSourceStr: '',
      signAmountStr: '',
      performanceDate: '',
      contractNo: '',
      categoryName: '',
    }
  },
  searchDetail: {
    url: 'http://10.10.37.57:4444/mock/detail.json',
    type: 'post',
  },
  logList: {
    url: 'http://10.10.37.57:4444/mock/logList.json',
    type: 'post',
  }
})
export default class Reservation extends Component {
  static displayName = 'Reservation';

  constructor(props) {
    super(props);
    this.state = {
      current: 1,
      dataSource: getData(),
      isShow: false,
      height: `${document.documentElement.clientHeight - 260}px`,
      loading: false,
      showTransfer: false,
      transferData: [],
      transferExtra: [],
      transferDefault: [],   //用于恢复默认显示
      transferValue: [],
      filterTableHeaders: [],
    };
  }

  componentDidMount () {
    this.props.updateBindingData('dataList',{
      data: {
        page: 1,
      },
    });

    setTimeout(function(){
      scrollbarObj = Scrollbar.init(document.querySelector('.scrollbar-table .next-table-body'), {
        alwaysShowTracks: false,
      });
      scrollbarObj.addListener((item) => {
        const {offset, limit} = item;
        // console.log('offset==',offset)
        // console.log('limit==',limit)
        document.querySelector('.scrollbar-table .next-table-header').scrollTo(offset.x,0)
      })
    })

    window.addEventListener('resize', this.handleHeight);
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.handleHeight);

    scrollbarObj.removeListener();
  }

  handleHeight = () => {
    const screenHeight = document.documentElement.clientHeight;
    let height = `${screenHeight - 260}px`;
    if (screenHeight < 472) {
      height = 'auto'
    }

    this.setState({
      height
    })
  }

  handlePagination = (current) => {
    let that = this;
    this.setState({
      loading: true,
    });
    setTimeout(() => {
      that.props.updateBindingData('dataList',{
        data: {
          page: current,
        },
        url: 'http://10.10.37.57:4444/mock/search'+current+'.json'
      });
      that.setState({
          loading: false,
          current,
      });
  }, 200);
  };

  handleSort = (dataIndex, order) => {
    const dataSource = this.state.dataSource.sort((a, b) => {
      const result = a[dataIndex] - b[dataIndex];
      if (order === 'asc') {
        return result > 0 ? 1 : -1;
      }
      return result > 0 ? -1 : 1;
    });

    this.setState({
      dataSource,
    });
  };


  showDetail = (event) => {
    event.stopPropagation();
                
    this.props.updateBindingData('searchDetail');
    this.props.updateBindingData('logList');
    this.setState({
        isShow: true
    })
  }

  renderOper = (value, index, record) => {
    return (
      <div></div>
    );
  };

  setCellProps = (rowIndex, colIndex, dataIndex, record) => {
    let that = this;
    if (colIndex === 1) {
        let propsConf = {
            style: {color: '#3ea8f5', cursor: 'pointer'},
            onClick: (event) => {
                event.stopPropagation();
                
                that.setState({
                    isShow: true,
                    loading: true,
                })
                setTimeout(function(){
                  that.props.updateBindingData('searchDetail');
                  that.props.updateBindingData('logList');
                  that.setState({
                    loading: false,
                })
                },500)
            },
        }
        return propsConf;
    }
  }

  setRowProps = (record, index) => {
    return {
        style: {height: '60px',fontSize: '14px'}
    }
  }

  hideShow = (event,obj) => {
      if (this.state.isShow) {
        this.setState({
            isShow: false
       })
      }
  }

  handleChange = (value, data, extra) => {
    this.setState({
      transferExtra: data,
      transferValue: value,
    })
  }

  saveTransferSet = () => {
    let _tableHeaders = [], that = this;
    const {transferExtra} = this.state;
    if (transferExtra.length > 0) {
      for (let i = 0; i < transferExtra.length; i++) {
        _tableHeaders.push({
          headerKey: transferExtra[i].value,
          headerName: transferExtra[i].label
        })
      }
    }
    this.setState({
      transferData: transferExtra,
      showTransfer: false,
      filterTableHeaders: _tableHeaders,
      loading: true,
    })
    Message.show({
      type: 'success',
      content: '修改成功！',
      hasMask: true,
      duration: 1000
    });

    setTimeout(function() {
      that.setState({
        loading: false,
      })

      let parsentW = document.querySelector('.scrollbar-table .scroll-content').offsetWidth;
      let childTableW = document.querySelector('.scrollbar-table .scroll-content table').scrollWidth;
      console.log(parsentW, childTableW)
      if (parsentW < childTableW) {
        document.querySelector('.scrollbar-table .next-table-header').setAttribute('style','margin-bottom:-15px');
      } else {
        document.querySelector('.scrollbar-table .next-table-header').setAttribute('style','margin-bottom:0');
      }
    }, 300)
  }

  handleTransfer = () => {
    let _transferData = [], _transferValue = [];
    const {tableHeaders} = this.props.bindingData.dataList;
    const {showTransfer, transferValue} = this.state;

    if (tableHeaders && tableHeaders.length > 0) {
      for(let i = 0; i < tableHeaders.length; i++) {
        _transferData.push({
            label: `${tableHeaders[i].headerName}`,
            value: `${tableHeaders[i].headerKey}`,
            disabled: i === 0
        })
        _transferValue.push(tableHeaders[i].headerKey);
      }
    }
    let _state = {
      showTransfer: !showTransfer,
      transferData: _transferData,
    };
    if (transferValue && transferValue.length == 0) {
      _state['transferValue'] = _transferValue;
      _state['transferDefault'] = _transferData;   //设置默认数据，用于恢复默认显示
    }
    this.setState(_state)

    document.querySelector('.scrollbar-table .next-table-header').setAttribute('style','margin-bottom:-15px');
  }

  restoreDefault = () => {
    let _tableHeaders = [], _transferValue = [], _transferData = [], that = this;
    const {transferDefault} = this.state;
    const {tableHeaders} = this.props.bindingData.dataList;
    if (transferDefault.length > 0) {
      for (let i = 0; i < transferDefault.length; i++) {
        _tableHeaders.push({
          headerKey: transferDefault[i].value,
          headerName: transferDefault[i].label
        })
        _transferData.push({
          label: `${tableHeaders[i].headerName}`,
          value: `${tableHeaders[i].headerKey}`,
          disabled: i === 0
        })
        _transferValue.push(transferDefault[i].value);
      }
    }
    this.setState({
      transferData: _transferData,
      transferValue: _transferValue,
      filterTableHeaders: _tableHeaders,
      showTransfer: false,
      loading: true,
    })
    Message.show({
      type: 'success',
      content: '恢复默认设置成功！',
      hasMask: true,
      duration: 1000
    });
    setTimeout(function() {
      that.setState({
        loading: false,
      })
    }, 300)
  }

  renderTableColumn = (headerDatas) => {
    if (headerDatas && headerDatas.length > 0) {
      return headerDatas.map((item, index) => {
        return (
          <Table.Column
            title={item.headerName}
            dataIndex={item.headerKey}
            key={index}
            cell={item.cell || ((value) => value)}
            width={220 || 'auto'}
            height={50}
            //lock={ index === 0 ? 'left' : false}
          />
        )
      })
    }
  }


  render() {

    const { isShow, loading, showTransfer, transferData, filterTableHeaders, transferValue } = this.state;
    const { dataList, searchDetail, logList } = this.props.bindingData;
    let tableDataValues, tableHeaders;
    if (dataList) {
      tableDataValues = dataList.tableDataValues;
      tableHeaders = dataList.tableHeaders;
    }
    let total = tableDataValues && tableDataValues.length;
    
    let setUp = (
      <div className="shezhi-icon" onClick={this.handleTransfer}>
        <FoundationSymbol size="small" type={'shezhi'} />
        <span className="shezhi-text">编辑显示字段</span>
      </div>
    )

    return (
      <Loading visible={loading} fullScreen shape="fusion-reactor">
        <div style={styles.tableContainer} onClick={this.hideShow}>
            {
                isShow ? (
                    <BasicDetailInfo searchDetail={searchDetail} logList={logList} hideShow={this.hideShow}/>
                ) : ""
            }

            {
              showTransfer ? (
                <div className="show-transfer">
                  <div className="transfer-content">
                    <div className="title">
                      <span>编辑显示字段</span>
                      <FoundationSymbol size="small" type={'cross'} onClick={this.handleTransfer}/>
                    </div>
                    <Transfer defaultValue={transferValue} dataSource={transferData} onChange={this.handleChange} titles={['不显示字段', '显示字段']} />
                    <div className="transfer-footer">
                      <div className="dialog-footer">
                        <section className="nb-button-wrapper large" style={{backgroundColor: 'rgb(217, 217, 217)'}} onClick={this.restoreDefault}>恢复默认</section>
                        <section className="nb-button-wrapper large" style={{backgroundColor: 'rgb(52, 151, 255)'}} onClick={this.saveTransferSet}>保存设置</section>
                      </div>
                    </div>
                  </div>
                </div>
              ) : ""
            }
            
            <Tab
              extra={setUp}
            >
                <Tab.Item title={tabs[0].tab} key={tabs[0].key}>
                  <Table
                      dataSource={tableDataValues ? tableDataValues : []}
                      onSort={this.handleSort}
                      hasBorder={false}
                      className="scrollbar-table"
                      rowSelection={{onChange: () => {}}}
                      getCellProps={this.setCellProps}
                      getRowProps={this.setRowProps}
                      id="reser-scrollbar"
                      fixedHeader={true}
                      maxBodyHeight={this.state.height}
                      //loading={this.state.loading}
                      >
                      {this.renderTableColumn(filterTableHeaders && filterTableHeaders.length > 0 ? filterTableHeaders : tableHeaders)}
                  </Table>
                  <Pagination
                      pageSize={20}
                      style={styles.pagination}
                      current={this.state.current}
                      onChange={this.handlePagination}
                      total={total} 
                      totalRender={total => `Total: ${total}`}
                      />
                </Tab.Item>
            </Tab>
        </div>
      </Loading>
    );
  }
}

const styles = {
  tableContainer: {
    background: '#fff',
    boxShadow: 'rgb(206, 205, 205) 0px 0px 14px 0px',
    WebkitBoxShadow: 'rgb(206, 205, 205) 0px 0px 14px 0px',
  },
  nbDetailWrapper: {

  },
  pagination: {
    margin: '20px 0',
    textAlign: 'center',
  },
  editIcon: {
    color: '#999',
    cursor: 'pointer',
  },
  circle: {
    display: 'inline-block',
    background: '#28a745',
    width: '8px',
    height: '8px',
    borderRadius: '50px',
    marginRight: '4px',
  },
  stateText: {
    color: '#28a745',
  },
};
